package co.com.javeriana.aes.patrones.universalbank.core.ldap;

import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

/**
 *
 * @author jonathan
 */
public class Connection {

    private static final String USER_NAME = "1136879159";
    private static final String PASSWORD = "Carmine17";
    private static final String DN = "cn=1136879159,cn=users,ou=groups,dc=test,dc=com";

    private static final String BASE = "dc=test,dc=com";
    private static final String LDAP_URL = "ldap://192.168.43.11:389";
    private static final String CONTEXT_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";
    private static final String SECURITY_AUTHENTICATION = "simple";

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        System.out.println(validateUser("1136879159", "Carmine17"));

    }

    public static boolean validateUser(String userName, String password) {

        boolean validate = false;

        Hashtable authEnv = new Hashtable();

        authEnv.put(Context.INITIAL_CONTEXT_FACTORY, CONTEXT_FACTORY);
        authEnv.put(Context.PROVIDER_URL, LDAP_URL);
        authEnv.put(Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION);

        //cn=1136879159,cn=users,ou=groups,dc=test,dc=com"
        String DN = "cn=" + userName + "," + "cn=users" + "," + "ou=groups" + "," + BASE;        
        authEnv.put(Context.SECURITY_PRINCIPAL, DN);
        authEnv.put(Context.SECURITY_CREDENTIALS, password);

        try {
            DirContext authContext = new InitialDirContext(authEnv);
            validate = true;
        } catch (NamingException namEx) {
            namEx.printStackTrace();
        }
        return validate;
    }
}
